﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using Newtonsoft.Json;
using T.FAS.Runtime.DataModel.Dao;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.ServiceComponent.DAC.Service;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Base.Dao;

namespace T.FAS.Runtime.DataModel.Dao
{
    public class StateMachineStateELBDao : DaoService<TState>
    {
        public override string TableName => "FAS_StateMachineState";
        public override string IDColumnName => "ID";
        public string ForeignColumn => "StateMachineID";

        public override List<string> ExceptColumnName {get;} = DaoUtil.GetExceptionColumn<TState>();

        public StateMachineStateELBDao() : base()
        {
            DBName = "TFAS";
        }

        /// <summary>
        /// 获取元数据内容
        /// </summary>
        /// <param name="metaDataId"></param>
        /// <returns></returns>
        public List<TState> GetTStatesByForeignKey(string smID)
        {
            var result = new List<TState>();
            if (string.IsNullOrEmpty(smID))
            {
                return result;
            }
            List<object> objects = base.GetObjectsByFilter($"{ForeignColumn}='{smID}'");
            if (objects != null)
            {
                foreach (var obj in objects)
                {
                    var state = obj as TState;
                    result.Add(state);
                }
            }
            return result.OrderBy(o => o.Sort).ToList();
        }

        /// <summary>
        /// 添加TState
        /// </summary>
        /// <param name="states"></param>
        public void CreateTState(List<TState> states)
        {
            try
            {
                DaoUtil.ExecuteInsertSQL(states, this);    //创建状态
            }
            catch (Exception e)
            {
                throw new FasException(DataModelErrorCode.SM.CreateStateError, e.Message, e);
            }
        }

        /// <summary>
        /// 删除TState
        /// </summary>
        /// <param name="smID"></param>
        public void DeleteTStateByForeignKey(string smID)
        {
            try
            {
                base.DB.ExecSqlStatement(string.Format(DaoUtil.DeleteSQLWithNoParam, this.TableName, this.ForeignColumn, smID));
            }
            catch (Exception e)
            {
                throw new FasException(DataModelErrorCode.SM.DeleteStateError, e.Message, e);
            }
        }

    }
}
